from flask import current_app, abort, render_template, session, g, request, jsonify

from info import db
from info.modules.news import news_blu

# 详情页面
from info.utils.common import user_login_data
from info.utils.models import News, User, UserCollection, Comment,CommentLike
from info.utils.response_code import RET, error_map


@news_blu.route('/<int:news_id>')
@user_login_data  # news_detail = user_login_data(news_detail)
def news_detail(news_id):
    # 查询某条新闻的数据  根据news_id
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    # 查询点击量排行前10的新闻
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)
        rank_list = []

    user = g.user

    # 查询该新闻是否被当前用户收藏
    is_collected = False  # 记录是否收藏

    if user:  # 用户已登录
        if news in user.collection_news:
            is_collected = True

    # 查询该新闻的所有评论  排序 时间倒序
    comments = []
    try:
        comments = news.comments.order_by(Comment.create_time.desc()).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()

        is_like = False
        if user:
            if comment in user.like_comments:
                is_like = True

        comment_dict["is_like"] = is_like
        comment_list.append(comment_dict)

    #查询作者是否被关注
    is_followed = False
    if news.user and user: #　如果新闻有作者并且用户以登陆
        if news.user in user.followed:
            is_followed = True

    user = user.to_dict() if user else None

    # 将新闻数据传入模板渲染
    return render_template("news/detail.html", news=news.to_dict(), user=user, rank_list=rank_list,
                           is_collected=is_collected, comments=comment_list, is_followed = is_followed)


# 新闻收藏
@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    # 判断用户是否登录
    user = g.user
    if not user:  # 用户未登录
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 获取出news_id对应的新闻模型
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 数据库行为: 添加/删除收藏记录 (使用关系属性来关联)
    if action == "collect":  # 收藏
        user.collection_news.append(news)
    else:  # 取消收藏
        user.collection_news.remove(news)

    # json返回结果
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 新闻评论
@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    news_id = request.json.get("news_id")
    comment_content = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # 校验参数
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为: 添加一条评论记录
    comment = Comment()
    comment.content = comment_content
    comment.news_id = news_id
    comment.user_id = user.id
    if parent_id:  # 如果有parent_id, 说明为子评论
        try:
            parent_id = int(parent_id)
            comment.parent_id = parent_id
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 添加到事务中
    db.session.add(comment)
    # 这里必须要手动提交 否则无法立即生成评论id并返回给前端
    try:
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 返回json  必须将评论id返回给前端, 以便前端构建子评论的parent_id
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=comment.to_dict())


# 点赞评论
@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # 数据库行为让用户和评论建立 / 解除点赞关系(使用关系属性)
    # 渲染方式局部刷新-> 前端渲染 -> json
    # 用户登陆状态
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])
    # 获取参数
    action = request.json.get("action")
    comment_id = request.json.get("comment_id")
    # 校验参数
    if not all([action,comment_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["add","remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 获取数据
    try:
        comment_id = int(comment_id)
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action == "add":
        user.like_comments.append(comment)
        comment.like_count += 1
    else:
        user.like_comments.remove(comment)
        comment.like_count -= 1
    # 返回结果
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])

#　实现关注的人
@news_blu.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    # 校验参数
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        user_id = int(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为
    try:
        author = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET, errmsg=error_map[RET])

    if action == "follow":
        user.followed.append(author)
    else:
        user.followed.remove(author)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])